import { useUserStore } from '@/stores/user';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const http = axios.create({
    baseURL: import.meta.env.DEV ? import.meta.env.VITE_BASE_URL : window.domain.url,
    timeout: 60000,
});

// 请求拦截器
http.interceptors.request.use(function (config) {
    const userStore = useUserStore();
    if (userStore.accessToken) {
        config.headers.Authorization = userStore.accessToken;
    }
    console.log('config', config);
    
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 响应拦截器
http.interceptors.response.use(
    response => {
        if (response.data.code === 401) {
            // 鉴权失败，跳转到登录页
            setTimeout(() => {
                window.location.href = "/login";
            }, 500);
        } else if (response.data.code === 500) {
            // 接口错误，提示错误
            ElMessage.error(response.data.msg);
        } else if (response.headers.authorization) {
            // 携带刷新令牌，替代当前令牌
            const userStore = useUserStore();
            userStore.accessToken = response.headers.authorization;
        }

        return response;
    }, error => {
        if (error.message.substring(0, 10) === 'timeout of') {
            ElMessage.error(`请求超时：${error.config.timeout / 1000}秒`);
            console.error(`请求超时：${error.config.timeout / 1000}秒 ${error.config.baseURL}${error.config.url}`);
        } else if (error.message === 'Network Error') {
            ElMessage.error('连接服务器失败');
            console.error(`连接服务器失败：${error.config.baseURL}${error.config.url}`);
        } else {
            ElMessage.error(error.message);
            console.error(`请求未知错误：${error.config.baseURL}${error.config.url}`);
        }
        return Promise.reject(error);
    });

export default http;
